import "./index.css";

import React, { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";

import { DatePicker, message } from "antd";
import axios from "axios";
import InterIP from "../../IP/IP";

import OtherComponent from "../othercomponents";

let IP = InterIP().props.children;

// 时间日期组件
const { RangePicker } = DatePicker;

function onChange(value, dateString) {
  console.log("Selected Time: ", value);
  console.log("Formatted Selected Time: ", dateString);
}

function onOk(value) {
  console.log("onOk: ", value);
}

export default function ConfirmOrder() {
  var userID = document.cookie.slice(5);

  const navigate = useNavigate();
  const loc = useLocation();
  const loca = loc.state || [];
  // console.log(loca);
  const [address, setAddress] = useState([]);
  const [shop, setShop] = useState([]);
  // 地址请求后台
  useEffect(() => {
    var userID = document.cookie.slice(5);
    axios
      .post("http://" + IP + ":3000/user/selAddress", {
        user_id: userID,
      })
      .then((res) => {
        setAddress((address) => (address = res.data));
      });
    axios.post('http://localhost:3000/index/selStore', {}).then((res) => {
      let arr = []
      loca.forEach((v, k) => {
        arr[k] = {
          store_id: '',
          store_name: v.store_name,
          boss_name: '',
          boss_phone: '',
          total_price: 0,
          product: [],
        }
      });
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i].store_name === arr[j].store_name) {
            arr.splice(j, 1);
            j--;
          }
        }
      }
      arr.forEach((v) => {
        loca.forEach((val) => {
          if (v.store_name === val.store_name) {
            let smallArr = {
              product_name: val.product_name,
              product_number: val.product_number,
              product_specification: val.product_specification,
              product_price: val.product_price,
              product_img: val.product_img,
              buy_number: val.buy_number,
              product_id: val.product_id
            }
            v.product.push(smallArr)
            v.total_price += parseFloat(val.product_price) * val.buy_number
          }
        })
      })
      res.data.forEach((value) => {
        arr.forEach((v) => {
          if (v.store_name === value.store_name) {
            v.store_id = value.store_id;
            v.boss_name = value.boss_name;
            v.boss_phone = value.boss_phone;
          }
        })
      })
      setShop((shop) => shop = arr);
    })
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  //修改默认地址
  function setDefaultAddresss(id, k) {
    return () => {
      axios
        .post("http://" + IP + ":3000/user/resetAddress", {
          default_address: "0",
          user_id: userID,
        })
        .then((res) => {
          axios
            .post("http://" + IP + ":3000/user/defaultAddress", {
              default_address: "1",
              address_id: id,
            })
            .then((res) => {
              axios
                .post("http://" + IP + ":3000/user/selAddress", {
                  user_id: userID,
                })
                .then((res) => {
                  setAddress((address) => (address = res.data));
                });
            });
        });
    };
  }

  // 删除地址
  function deleteAddress(k, id) {
    return () => {
      axios
        .post("http://" + IP + ":3000/user/delAddress", {
          address_id: id,
        })
        .then((res) => {
          console.log(res);
          setAddress(
            (address) =>
            (address = address.filter((v, key) => {
              return !(key === k);
            }))
          );
        });
    };
  }

  // 修改地址
  function bjsite(data) {
    return () => {
      navigate("/home/confirmorder/changeaddress", {
        state: {
          data: data,
        },
      });
    };
  }

  // 添加新地址
  function addAddress() {
    navigate("/home/confirmorder/addaddress");
  }

  // 返回购物车
  function backShoppingCart() {
    navigate("/home/shoppingCart");
  }
  // 求最终价格
  var sumMoneyAll = 0;
  for (let i = 0; i < shop.length; i++) {
    sumMoneyAll += shop[i].total_price + 5;
  }
  // 提交订单
  var onOff = true;
  function submitOrder() {
    // 获取当前时间
    let date = new Date(+new Date() + 8 * 3600 * 1000)
      .toISOString()
      .replace(/T/g, " ")
      .replace(/\.[\d]{3}Z/, "");

    // 地址选中
    var oAddress = document.getElementsByClassName("addressclass");
    var address_id = '';
    for (let i = 0; i < oAddress.length; i++) {
      if (oAddress[i].checked) {
        address_id = oAddress[i].value;
      }
    }
    if (onOff && address_id) {
      onOff = false;
      // 通过地址ID查询 请求后台
      let addressID = parseInt(address_id);
      axios
        .post("http://" + IP + ":3000/index/getaddress", {
          address_id: parseInt(address_id),
        })
        .then((res) => {
          let address_id = res.data[0].address_id;
          let address_name = res.data[0].consignee;
          let address = res.data[0].area + " " + res.data[0].street
          let address_phone = res.data[0].contact_phone;

          // 提交订单数据(多并发请求后台)
          for (let i = 0; i < loca.length; i++) {
            axios.post('http://' + IP + ':3000/user/addIndent', {
              order_time: date,
              store_name: loca[i].store_name,
              order_status: '待付款',
              total_price: sumMoneyAll,
              freight: '5.00',
              user_id: userID,
              product_id: loca[i].product_id,
              order_evaluate: '0',
              product: `{"product_name":"${loca[i].product_name}","product_number":${loca[i].product_number},"product_specification":"${loca[i].product_specification}","product_price":${loca[i].product_price},"product_img":"${loca[i].product_img}","buy_number":${loca[i].buy_number},"product_id":${loca[i].product_id}}`,
              address_id,
              address_name,
              address,
              address_phone,
              boss_name: loca[i].boss_name,
              boss_phone: loca[i].boss_phone
            }).then((res) => {
              if (res.data.msg === '已添加到订单') {
                for (let i = 0; i < loca.length; i++) {
                  var cartIDArr = [];
                  cartIDArr.push(loca[i].cart_id)
                  // 后台删除商品
                  axios.post("http://" + IP + ":3000/index/delgoods", { cart_id: cartIDArr }).then((res) => {
                    if (res.data.code) {
                      navigate("/home/submitsuccess/apay", { state: { sumMoneyAll, date, address_id: addressID, shops: 1 } });
                    }
                  })
                }
              }
            })
          }
        })
    } else {
      if (address_id) {
        message.warning('别他妈点了!!!');
        message.warning('你想多付点钱，我也不介意!!!');
        message.loading("请等待!")
      } else {
        message.warning('你想送哪,送给我吗???')
      }
    }


  }

  return (
    <div className="tyc_confirmorder">
      <div className="tyc_address">
        <ul className="tyc_address_ul">
          <li className="tyc_fristli" onClick={backShoppingCart}>
            我的购物车
          </li>
          <li className="tyc_middleli">确认订单信息</li>
          <li className="tyc_lastli">订单提交成功</li>
        </ul>
        {/* 收货人信息 */}
        <div className="tyc_address_component">
          <h3>
            <i>收货人信息</i>
            <button className="tyc_new_address_btn1" onClick={addAddress}>
              使用新地址
            </button>
          </h3>
          <ul className="tyc_address_message">
            {address.map((v, k) => {
              return (
                <li key={v.address_id}>
                  <input
                    type="radio"
                    name="address"
                    id={"tyc_address" + k}
                    className="addressclass"
                    value={v.address_id}
                  />
                  <label htmlFor={"tyc_address" + k}>
                    {v.consignee} {v.area} {v.street} {v.contact_phone}{" "}
                    {v.comment}
                  </label>
                  {v.default_address === "1" ? <span>默认地址</span> : ""}
                  {v.default_address === "0" ? (
                    <strong onClick={setDefaultAddresss(v.address_id, k)}>
                      设置为默认地址
                    </strong>
                  ) : (
                    ""
                  )}

                  <div>
                    <em onClick={bjsite(v)}>修改</em>
                    <i onClick={deleteAddress(k, v.address_id)}>删除</i>
                  </div>
                </li>
              );
            })}
          </ul>
          <div className="tyc_more_address">
            <span>展开其他地址</span>
            <span>收起地址</span>
          </div>
        </div>
      </div>

      <div className="tyc_mallmessage">
        <h3>商品信息</h3>
        {shop.map((v, k) => {
          return (
            <div key={k}>
              <table border="1">
                <thead>
                  <tr>
                    <th className="tyc_mallName">
                      <span>{v.store_name}</span>
                    </th>
                    <th className="tyc_specification">规格</th>
                    <th className="tyc_onePrice">单价</th>
                    <th className="tyc_num">数量</th>
                    <th className="tyc_sumOnePrice">金额</th>
                  </tr>
                </thead>
                <tbody>
                  {shop[k].product.map((value, key) => {
                    return (
                      <tr key={key}>
                        <td className="tyc_mail">
                          <div>
                            <img src={value.product_img} alt="" />
                          </div>
                          <span>{value.product_name}</span>
                        </td>
                        <td>
                          {value.product_number}
                          {value.product_specification}
                        </td>
                        <td>
                          ￥<i>{value.product_price}</i>
                        </td>
                        <td className="tyc_addsub_btn">
                          <div>-</div>
                          <input
                            type="text"
                            defaultValue={value.buy_number}
                            key={value.buy_number}
                            className={`buyNum${k}`}
                          />
                          <div>+</div>
                        </td>
                        <td>
                          ￥
                          <i className={`tyc_money${k}`}>
                            {(
                              parseFloat(value.product_price) * value.buy_number
                            ).toFixed(2)}
                          </i>
                        </td>
                      </tr>
                    );
                  })}

                  <tr>
                    <td colSpan="7" className="tyc_sumPrice">
                      <span>运费</span>
                      <strong>￥5.0</strong>
                      <span>商品金额</span>
                      <strong>
                        ￥<span>{v.total_price.toFixed(2)}</span>
                      </strong>
                      <span>商家合计</span>
                      <strong>
                        ￥
                        <span>
                          {parseFloat(v.total_price + 5).toFixed(2)}
                        </span>
                      </strong>
                    </td>
                  </tr>
                </tbody>
              </table>
              <OtherComponent />
            </div>
          );
        })}
      </div>
      <div className="tyc_delivery_time">
        <h3>次日达·礼拜五专享</h3>
        <div>
          <span>选择配送时间：</span>

          <RangePicker
            style={{ width: "300px" }}
            showTime={{ format: "HH:mm" }}
            format="YYYY-MM-DD HH:mm"
            onChange={onChange}
            onOk={onOk}
          />
        </div>
      </div>
      <div className="tyc_settlement">
        <p>
          <strong>实付金额：</strong>
          <em>￥{sumMoneyAll.toFixed(2)}</em>
        </p>
        <div>
          <i>订单完成后可获得积分：</i>
          <span>{sumMoneyAll}积分</span>
        </div>
        <div>
          <button onClick={submitOrder}>提交订单</button>
        </div>
      </div>
    </div>
  );
}
